<template>
  <div>
    <van-cell
      class="avatar"
      title="头像"
      center
      clickable
      @click="dialogShow = true"
    >
      <img v-if="avatarImg" :src="avatarImg" />
      <img v-else src="@/assets/avatar.jpg" />
    </van-cell>
    <van-dialog
      v-model="dialogShow"
      title="标题"
      confirm-button-text="取消"
      close-on-click-overlay
    >
      <van-grid column-num="3">
        <van-grid-item>
          <img src="~@/assets/拍照.png" alt="" />
          <span>拍照</span>
          <span>(未开放)</span>
        </van-grid-item>
        <van-grid-item>
          <img src="~@/assets/图片.png" alt="" />
          <span>图片库</span>
          <van-uploader class="uploader" :after-read="afterRead" />
        </van-grid-item>
        <van-grid-item>
          <img src="~@/assets/随机.png" alt="" />
          <span>随机</span>
          <span>(未开放)</span>
        </van-grid-item>
      </van-grid>
    </van-dialog>
  </div>
</template>

<script>
import { getUploadAPI } from "@/network/api";
export default {
  name: "UploadAvatar",
  props: ["avatarImg"],
  data() {
    return {
      dialogShow: false, //弹窗
    };
  },
  methods: {
    afterRead(file) {
      let formData = new FormData();
      formData.append("file", file.file); //左边的"file"是后端定义的键名

      getUploadAPI(formData)
        .then((res) => {
          console.log(res);
          // 上传成功，返回成功的图片路径,并发送给父组件保存到userInfoList
          this.$emit("updataAvatar", res.data.url);

          this.dialogShow = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style scoped  lang="less" >
.avatar {
  img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }
}
.uploader {
  position: absolute;
  opacity: 0;
}
</style>